# encoding=utf-8
import sys
import time

import win32serviceutil
import win32service
import win32event
import os
import servicemanager
import winerror
import win32timezone

# windows服务测试，参照https://www.cnblogs.com/zoro-robin/p/6110188.html
from py.uitls.Logger import myLogger


class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "PythonService"  # 服务名
    _svc_display_name_ = "Python Service Test"  # 服务在windows系统中显示的名称
    _svc_description_ = "This is a python service test code "  # 服务的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.run = True

    def SvcDoRun(self):
        myLogger.info("service is run....")

        while self.run:
            myLogger.info("I am runing....")
            time.sleep(2)

    def SvcStop(self):
        myLogger.info("service is stop....")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.run = False


if __name__ == '__main__':
    if len(sys.argv) == 1:
        # 这段代码必须存在，否则会导致启动服务时1053错误
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(PythonService)
